<script setup lang="ts">
import { ref, onMounted } from 'vue'
import {
    Edit,
    Delete
} from '@element-plus/icons-vue'
// import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormItemConfig,SupplierModel,Supplier } from "@/pages/purchase/components/Supplier"


import { supplierApi } from '@/pages/purchase/components/Supplier'
import type { FormRules } from 'element-plus'
const formRef = ref()

// 表单校验规则
const rules = ref<FormRules>({
  name: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
  score: [{ required: true, message: '请输入评分', trigger: 'blur' }],
  contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  contactPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
})


const createFormConfig = <T extends FormItemConfig[]>(config: [...T]) => config;
const ListFields = [
    {
      label: 'ID',
      prop: 'supplierId',
      type: 'input',
      disabled: false,
      width: "100px",
    },
    {
      label: '名称',
      prop: 'name',
      type: 'input',
      // width: "250px",
    },
    {
      label: '评分',
      prop: 'score',
      type: 'input',
      width: "250px",
    },
    {
      label: '联系人',
      prop: 'contactPerson',
      type: 'input',
      width: "350px",
    },
    {
      label: '联系电话',
      prop: 'contactPhone',
      type: 'input',
      width: "350px",
    },
    {
      label: '操作',
      prop: 'action',
      slot: true,
      width: "160px"
    },
];
const formConfig = createFormConfig([
  { 
    type: 'input', 
    label: '供应商名称', 
    prop: 'name', 
    placeholder: '请输入供应商名称' 
  },
  { 
    type: 'input', 
    label: '评分', 
    prop: 'score', 
    placeholder: '请输入评分', 
    inputType: 'number' 
  },
  { 
    type: 'input', 
    label: '联系人', 
    prop: 'contactPerson', 
    placeholder: '请输入联系人' 
  },
  { 
    type: 'input', 
    label: '联系电话', 
    prop: 'contactPhone', 
    placeholder: '请输入联系电话' 
  },
])

let supplierList = ref<Supplier[]>();
const formModel = ref<SupplierModel>({
  isUpdate:null,
  supplierId:null,
  name: '',
  score: null,
  contactPerson: '',
  contactPhone: '',
})
const bufferName = [
  { add: "添加供应商" },
  { edit:"编辑供应商"}
]
const titleName = "供应商管理";
const searchMessage = ref({
  name:'',
  contactPerson:'',
})

const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(100)

const title = ref('')
const visibleDrawer = ref(false)

onMounted(async () => {
  init();
})
const init = async () => {
  getDataListWithCondition();
}
const getDataListWithCondition = async () => {
    let params = {
        page: pageNum.value,
        size: pageSize.value,
        name: searchMessage.value.name ? searchMessage.value.name : null,
        contactPerson: searchMessage.value.contactPerson ? searchMessage.value.contactPerson : null,
    }
    console.log(params);
    const supplierListResponse = await supplierApi.getSupplierList(params);
    supplierList.value = supplierListResponse.data.records;
    console.log(supplierListResponse)    
    console.log(supplierList)
    total.value = supplierListResponse.data.total;
}
getDataListWithCondition();

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (formModel.value.isUpdate) {
        await supplierApi.updateSupplier(formModel.value.supplierId!, formModel.value)
        ElMessage.success('更新成功')
      } else {
        await supplierApi.addSupplier(formModel.value)
        ElMessage.success('添加成功')
      }
      visibleDrawer.value = false
      getDataListWithCondition()
    } else {
      ElMessage.error('请填写完整表单信息')
    }
  })
}


const clearData = () => {
  (Object.keys(formModel.value) as Array<keyof SupplierModel>).forEach(key => {
    formModel.value[key] = null;
  });
}

const showAddDrawer = () => {
    clearData()
    title.value = bufferName[0].add!
    visibleDrawer.value = true;
    formModel.value.isUpdate = false
}
const showEditDrawer = (row:Supplier) => {
    title.value = bufferName[1].edit!
    visibleDrawer.value = true
    formModel.value = {
      isUpdate: true,
      supplierId:row.supplierId,
      name: row.name,
      score: row.score,
      contactPerson: row.contactPerson,
      contactPhone: row.contactPhone,
    }
    console.log(formModel.value);

}

const deletefor = async (supplierId:number) => {
  await supplierApi.deleteSupplier(supplierId);
  getDataListWithCondition();
}

const deleteBox = (supplierId:number) => {
    ElMessageBox.confirm(
        '您确定要删除这条记录吗',
        '注意',
        {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
    .then(() => {
        deletefor(supplierId)
    })
    .catch(() => {
        ElMessage({
            type: 'info',
            message: '删除取消',
        })
    })
}

const search = () => {
    getDataListWithCondition()
    ElMessage('获取成功')
}
const searchWithNoCondition = () => {
    searchMessage.value = { name: '', contactPerson: '' };
    getDataListWithCondition()
    ElMessage('获取成功')
}

const onSizeChange = (size: number) => {
    pageSize.value = size
    getDataListWithCondition()
    ElMessage('获取成功')

}
const onCurrentChange = (num: number) => {
    pageNum.value = num
    getDataListWithCondition()
    ElMessage('获取成功')
}
const handleDrawerClose = () => {
  formRef.value?.clearValidate(); // 清除爆红
}

</script>

<template>
  <el-card class="page-container">
    <template #header>
        <div class="header">
            <span>{{ titleName }}</span>
            <div class="extra">
                <el-button type="primary" @click="showAddDrawer()">{{ bufferName[0].add }}</el-button>
            </div>
        </div>
    </template>
    <el-form inline>
      <el-form-item label="名称:">
          <el-input v-model="searchMessage.name" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="联系人:">
          <el-input v-model="searchMessage.contactPerson" placeholder="请输入"></el-input>
      </el-form-item>       
      <el-form-item>
      <el-button type="primary" @click="search()">搜索</el-button>
         <el-button @click="searchWithNoCondition()">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="supplierList" style="width: 100%">
      <el-table-column
        v-for="col in ListFields"
        :key="col.prop"
        :label="col.label"
        :prop="col.prop"
        :width="col.width"
      >
        <template v-if="col.slot" #default="scope">
          <template v-if="col.prop === 'action'">
            <el-button
              :icon="Edit"
              circle
              plain
              type="primary"
              @click="showEditDrawer(scope.row)"
            ></el-button> 
            <el-button
              :icon="Delete"
              circle
              plain
              type="danger"
              @click="deleteBox(scope.row.supplierId)"
            ></el-button>
          </template>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 7, 10]"
        layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
        @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />

        
        <el-drawer 
  v-model="visibleDrawer" 
  :title="title" 
  direction="rtl" 
  size="50%" 
  @close="handleDrawerClose">
    <el-form 
  ref="formRef"
  :model="formModel" 
  :rules="rules" 
  label-width="120px"
>

      <template v-for="(item, index) in formConfig" :key="index" >
        <el-form-item v-if="item.type === 'input'" :label="item.label" :prop="item.prop">
          <el-input 
            v-model="formModel[item.prop]"
            :placeholder="item.placeholder"
            :type="item.type"
          ></el-input>
        </el-form-item>
        
        <el-form-item v-else-if="item.type === 'datetime'" :label="item.label" :prop="item.prop">
          <el-date-picker
            v-model="formModel[item.prop]"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            :placeholder="item.placeholder"
          />
        </el-form-item>

        <!-- <el-form-item v-else-if="item.type === 'select'" :label="item.label">
          <el-select
            v-model="formModel[item.prop]"
            :placeholder="item.placeholder"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="option in item.options"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item> -->
      </template>

      <el-form-item>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>

    
  </el-card>
</template>



<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}

.editor {
    width: 100%;

    :deep(.ql-editor) {
        min-height: 200px;
    }
}
</style>